package kr.saeildamil.androidstudy.ch19;

import kr.saeildamil.androidstudy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class AsyncTaskBasic extends Activity {
	int mValue;
	TextView mText;
	ProgressDialog mProgress;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_longtime);
	}

	public void mOnClick(View v) {
		new AsyncTaskTest().execute(100);
	}

	class AsyncTaskTest extends AsyncTask<Integer, Integer, Integer> {
		// 즉 , AsyncTask<params, values, result>위와 확장자가 같아야함
		protected Integer doInBackground(Integer... params) {
			Log.d("AsyncTask", "doInBackground Params" + params[0]);
			while (!isCancelled()) {
				mValue++;
				if (mValue <= 100) {
					publishProgress(mValue);
				} else {
					break;
				}
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
				}
			}
			return mValue;
		}

		protected void onCancelled() {
			Log.d("AsyncTask", "onCancelled()");
			super.onCancelled();
			mProgress.dismiss();
		}

		protected void onCancelled(Integer result) {
			Log.d("AsyncTask", "onCancelled result" + result);
			super.onCancelled(result);
			mProgress.dismiss();
		}

		protected void onPostExecute(Integer result) {
			Log.d("AsyncTask", "onPostExecute result" + result);
			super.onPostExecute(result);
			mProgress.dismiss();
		}

		protected void onPreExecute() {
			Log.d("AsyncTask", "onPreExecute()");
			super.onPreExecute();
			mValue = 0;
			mProgress = new ProgressDialog(AsyncTaskBasic.this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("업뎃중임ㅋㅋ");
			mProgress.setMessage("기다리셈...");
			mProgress.setCancelable(false);
			mProgress.setProgress(0);
			mProgress.setButton(DialogInterface.BUTTON_POSITIVE, "취소",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							cancel(true);
						}
					});
			mProgress.show();

		}

		protected void onProgressUpdate(Integer... values) {
			Log.d("AsyncTask", "onProgressUpdate Progress" + values[0]);
			super.onProgressUpdate(values);
			mProgress.setProgress(values[0]);
			mText.setText(Integer.toString(values[0]));
		}

	}
}
